#include "table.h"

/**
 * 快速排序
 * @param {table} *tab
 * @param {int} left
 * @param {int} right
 * @return {void}
 */
void quicksort(table *tab, int left, int right) {
    int i, j;

    if(left < right) {
        i = left;
        j = right ;
        tab -> r[0] = tab -> r[i];

        do{
            while (tab -> r[j].key >= tab -> r[0].key && i < j)
            {
                j--;
            }

            if(i < j)
            {
                tab -> r[i].key = tab -> r[j].key;
                i++;
            }
            

            while (tab -> r[i].key <= tab -> r[0].key && i < j)
            {
                i++;
            }

            if(i < j)
            {
                tab -> r[j].key = tab -> r[i].key;
                j--;
            }
            
        } while(i != j);

        tab -> r[i] = tab -> r[0];
        quicksort(tab, left, i - 1);
        quicksort(tab, i + 1, right);
    }
}

int main() {
    table tab;
    int i;

    int arr[] = {0, 49, 38, 65, 97, 76, 13, 27, 49};

    tab.length = 0;

    for (i = 1; i <= 8; i++)
    {
        tab.r[i].key = arr[i];
        tab.length++;
    }

    quicksort(&tab, 1, tab.length);

    for (i = 1; i <= tab.length; i++)
    {
        printf("%2d ", tab.r[i].key);
    }

    return 0;
}